package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/category")
@Slf4j
public class CategoryController {

    @Autowired
    private CategoryService service;

    @PostMapping
    public R<String> save(@RequestBody Category category){
        log.info("执行添加分类操作,入参:{}",category);
        service.save(category);
        return R.success("添加分类成功!");
    }

    @PutMapping
    public R<String> update(@RequestBody Category category){
        log.info("执行修改分类操作,入参:{}",category);
        service.updateById(category);
        return R.success("修改分类成功!");
    }

    @GetMapping("/page")
    public R<Page<Category>> selectByPage(int page,int pageSize){
        //构建分页构造器
        Page<Category> iPage = new Page<>(page,pageSize);

        //构建查询条件构造器
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByAsc(Category::getSort);
        Page<Category> res = service.page(iPage, wrapper);
        log.info("执行查询分类操作,出参:{}",res);

        //返回查询结果
        return R.success(res);
    }

    @GetMapping("/list")
    public R<List<Category>> list(Integer type){
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        //设置匹配条件
        wrapper.eq(type != null ,Category::getType,type);
        //设置排序条件
        wrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);

        List<Category> list = service.list(wrapper);
        log.info("执行查询所有分类操作,出参:{}",list);

        //返回查询结果
        return R.success(list);
    }

    @DeleteMapping
    public R<String> delete(Long id){
        log.info("执行删除分类操作,入参:{}",id);
        service.remove(id);
        return R.success("删除分类成功!");
    }
}
